from fastapi import APIRouter, Depends, Form, Request, Query, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session
from typing import Optional
from ..models import get_db, Contact, User, WebsiteConfig
from ..auth import get_current_user
from ..utils import paginate_query, get_icon_by_type
import os
from fastapi.templating import Jinja2Templates

router = APIRouter()

# 获取模板目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))

# 联系方式列表页面
@router.get("/contacts", response_class=HTMLResponse)
async def admin_contacts(
    request: Request, 
    page: int = Query(1, ge=1), 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    query = db.query(Contact)
    pagination = paginate_query(query, page, 20)
    
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="gradient")
    
    return templates.TemplateResponse("admin/contacts.html", {
        "request": request, 
        "contacts": pagination["items"],
        "current_page": pagination["current_page"],
        "total_pages": pagination["total_pages"],
        "total_items": pagination["total_items"],
        "page_size": pagination["page_size"],
        "current_user": current_user,
        "config": config
    })

# 添加联系方式页面
@router.get("/contacts/add", response_class=HTMLResponse)
async def admin_add_contact(
    request: Request, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/contact-form.html", 
        {"request": request, "action": "add", "current_user": current_user, "config": config}
    )

# 编辑联系方式页面
@router.get("/contacts/edit/{contact_id}", response_class=HTMLResponse)
async def admin_edit_contact(
    request: Request, 
    contact_id: int, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    contact = db.query(Contact).filter(Contact.id == contact_id).first()
    if not contact:
        raise HTTPException(status_code=404, detail="联系方式不存在")
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/contact-form.html", 
        {"request": request, "contact": contact, "action": "edit", "current_user": current_user, "config": config}
    )

# 保存联系方式
@router.post("/contacts/save")
async def save_contact(
    request: Request,
    id: Optional[int] = Form(None),
    name: str = Form(...),
    type: str = Form(...),
    url: str = Form(...),
    is_active: bool = Form(False),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # 根据类型自动设置图标
    icon = get_icon_by_type(type)
    
    if id:
        contact = db.query(Contact).filter(Contact.id == id).first()
        if not contact:
            raise HTTPException(status_code=404, detail="联系方式不存在")
        contact.name = name
        contact.type = type
        contact.url = url
        contact.icon = icon
        contact.status = is_active
    else:
        contact = Contact(
            name=name,
            type=type,
            url=url,
            icon=icon,
            status=is_active
        )
        db.add(contact)
    db.commit()
    return RedirectResponse(url="/admin/contacts", status_code=302)

# 删除联系方式
@router.post("/contacts/delete/{contact_id}")
async def delete_contact(
    contact_id: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    contact = db.query(Contact).filter(Contact.id == contact_id).first()
    if not contact:
        # 检查是否是异步请求
        is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
        if is_ajax:
            return {"success": False, "message": "联系方式不存在"}
        else:
            raise HTTPException(status_code=404, detail="联系方式不存在")
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    db.delete(contact)
    db.commit()
    
    if is_ajax:
        # 对于异步请求，返回JSON响应
        return {"success": True, "message": "删除成功"}
    else:
        # 对于普通请求，返回重定向
        return RedirectResponse(url="/admin/contacts?message=删除成功", status_code=302)

# 批量删除联系方式
@router.post("/contacts/batch-delete")
async def batch_delete_contacts(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    form_data = await request.form()
    contact_ids = form_data.getlist("contact_ids")
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if contact_ids:
        # 将字符串ID列表转换为整数列表
        contact_ids = [int(id) for id in contact_ids]
        # 批量删除选中的联系方式
        db.query(Contact).filter(Contact.id.in_(contact_ids)).delete(synchronize_session=False)
        db.commit()
        
        if is_ajax:
            # 对于异步请求，返回JSON响应
            return {"success": True, "message": "批量删除成功"}
        else:
            # 对于普通请求，返回重定向
            return RedirectResponse(url="/admin/contacts?message=批量删除成功", status_code=302)
    else:
        if is_ajax:
            # 对于异步请求，返回JSON响应
            return {"success": False, "message": "请选择要删除的联系方式"}
        else:
            # 对于普通请求，返回重定向
            return RedirectResponse(url="/admin/contacts?message=请选择要删除的联系方式", status_code=302)

# 切换联系方式状态
@router.post("/contacts/toggle-status/{contact_id}")
async def toggle_contact_status(
    contact_id: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    contact = db.query(Contact).filter(Contact.id == contact_id).first()
    if not contact:
        if is_ajax:
            return {"success": False, "message": "联系方式不存在"}
        else:
            raise HTTPException(status_code=404, detail="联系方式不存在")
    
    try:
        # 切换状态
        contact.status = not contact.status
        db.commit()
        
        if is_ajax:
            return {"success": True, "message": "状态更新成功", "new_status": contact.status}
        else:
            return RedirectResponse(url="/admin/contacts", status_code=302)
    except Exception as e:
        db.rollback()
        if is_ajax:
            return {"success": False, "message": f"状态更新失败: {str(e)}"}
        else:
            raise HTTPException(status_code=500, detail="状态更新失败")